package com.zz.framework.core.ext

import android.content.res.Resources
import android.util.TypedValue
import android.widget.LinearLayout
import com.google.android.material.tabs.TabLayout
import java.lang.reflect.Field

/**
 * Copyright © 2021 StariverPool All rights reserved.
 * Created on 2021/6/6 5:21 下午.
 * @version: V1.0
 */
fun TabLayout.setIndicator(leftDip: Int, rightDip: Int) {
    val tabLayout: Class<*> = this.javaClass
    var tabStrip: Field? = null
    try {
        tabStrip = tabLayout.getDeclaredField("mTabStrip")
    } catch (e: NoSuchFieldException) {
        e.printStackTrace()
    }
    tabStrip?.setAccessible(true)
    var llTab: LinearLayout? = null
    try {
        llTab = tabStrip?.get(this) as? LinearLayout
    } catch (e: IllegalAccessException) {
        e.printStackTrace()
    }
    val left = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip.toFloat(), Resources.getSystem().getDisplayMetrics()).toInt()
    val right = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip.toFloat(), Resources.getSystem().getDisplayMetrics()).toInt()
    llTab?.children?.forEach { child ->
        run {
            child.setPadding(0, 0, 0, 0)
            val params = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f)
            params.leftMargin = left
            params.rightMargin = right
            child.layoutParams = params
            child.invalidate()
        }
    }
}